package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.OverflowListGoodsDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.OverflowList;
import com.atguigu.jxc.entity.OverflowListGoods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.OverflowListGoodsService;
import com.atguigu.jxc.util.DateUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

@Service
public class OverflowListGoodsServiceImpl implements OverflowListGoodsService {
    @Autowired
    private OverflowListGoodsDao overflowListGoodsDao;
    @Autowired
    private UserDao userDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean save(OverflowList overflowList, String overflowListGoodsStr, String overflowNumber) {
        //获取用户名
        User user = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());
        overflowList.setUserId(user.getUserId());
        overflowList.setOverflowNumber(overflowNumber);
        //保存商品报溢单
        overflowListGoodsDao.saveOverflow(overflowList);
        //声明一个返回值
        Boolean flag = false;
        Gson gson=new Gson();
        List<OverflowListGoods> list = gson.fromJson(overflowListGoodsStr,new TypeToken<List<OverflowListGoods>>(){}.getType());
        for (OverflowListGoods overflowListGoods : list) {
            overflowListGoods.setOverflowListId(overflowList.getOverflowListId());
            flag = overflowListGoodsDao.saveOverflowListGoods(overflowListGoods);
        }
        return flag;
    }

    /**
     * 查询报溢单列表
     * @param sTime
     * @param eTime
     * @return
     */
    @SneakyThrows
    @Override
    public List<OverflowList> getList(String sTime, String eTime) {
        ArrayList<OverflowList> overflowLists = new ArrayList<>();
        List <OverflowList> list = overflowListGoodsDao.selectList();
        List<String> timeSlotByDay = DateUtil.getTimeSlotByDay(sTime, eTime);
        for (OverflowList overflowList : list) {
            if ( timeSlotByDay.contains(overflowList.getOverflowDate())){
                overflowLists.add(overflowList);
            }
        }
        return overflowLists;
    }

    /**
     * 查询报溢单下边的商品
     * @param overflowListId
     * @return
     */
    @Override
    public List<OverflowListGoods> getGoodsList(Integer overflowListId) {
        List<OverflowListGoods> list = overflowListGoodsDao.selectGoodsList(overflowListId);
        return list;
    }
}
